package groupOne.app.DWD.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import groupOne.app.BaseAppOneStream;
import groupOne.common.Constant;
import groupOne.util.AtguiguUtil;
import groupOne.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 获取每天登录的用户，并去重
 */
public class Dwd_03_DwdTrafficUniqueVisitorDetail extends BaseAppOneStream {
    public static void main(String[] args) {
        new Dwd_03_DwdTrafficUniqueVisitorDetail().init(2003,2,"Dwd_03_DwdTrafficUniqueVisitorDetail", Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        stream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(s);
                    collector.collect(jsonObject);
                } catch (Exception e) {
                    System.out.println("数据格式不对");
                }
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
        .withTimestampAssigner((a,b) -> a.getLong("ts")))
                .keyBy(a -> a.getJSONObject("common").getString("uid"))
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<JSONObject, String, String, TimeWindow>() {

                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                    }

                    @Override
                    public void process(String s, Context context, Iterable<JSONObject> iterable, Collector<String> collector) throws Exception {
                        //获取每天的第一个窗口的的数据
                        String today = AtguiguUtil.toDate(context.window().getStart());
                        if (!today.equals(dateState.value())) {
                            dateState.update(today);
                            collector.collect(iterable.iterator().next().toJSONString());

                        }
                    }
                })
                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL));
    }
}
